import { useState, useEffect } from 'preact/hooks';
import { isConnected } from '../app';

export default function OnboardPeripherals() {
  const [buzzerState, setBuzzerState] = useState(false);
  const [buzzerFrequency, setBuzzerFrequency] = useState(2731);
  const [temperature, setTemperature] = useState(0);
  const [accuracy, setTemperatureAccuracy] = useState(0.25);

  // 蜂鸣器控制函数
  const handleBuzzerToggle = async () => {
    try {
      const response = await fetch('/api/buzzer', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
          state: !buzzerState,
          frequency: buzzerFrequency
        }),
      });

      if (response.ok) {
        setBuzzerState(!buzzerState);
      }
    } catch (error) {
      console.error('蜂鸣器控制失败:', error);
    }
  };

  // 蜂鸣器频率控制函数
  const handleFrequencyChange = async (frequency) => {
    setBuzzerFrequency(frequency);
    
    if (buzzerState) {
      try {
        const response = await fetch('/api/buzzer', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ 
            state: true,
            frequency: frequency
          }),
        });

        if (!response.ok) {
          console.error('蜂鸣器频率设置失败:', response.status);
        }
      } catch (error) {
        console.error('蜂鸣器频率设置失败:', error);
      }
    }
  };


  // 实时获取温度数据
  useEffect(() => {
    if (!isConnected.value) return;

     const fetchTemperature = async () => {
       try {
         const response = await fetch('/api/temperature');
         if (response.ok) {
           const data = await response.json();
           setTemperature(data.temperature || 0.0);
           setTemperatureAccuracy(data.accuracy || 0.25);
         } else {
           console.error('温度获取失败:', response.status);
         }
       } catch (error) {
         console.error('温度获取失败:', error);
       }
     };

    // 立即获取一次
    fetchTemperature();
    
    // 设置1秒更新周期
    const interval = setInterval(fetchTemperature, 1000);
    return () => clearInterval(interval);
  }, [isConnected.value]);


  return (
    <div class="h-full p-6">
      <div class="mb-6">
        <h1 class="text-xl font-medium flex items-center adonis-section-title">
          <div class="w-1 h-5 mr-3" style={{ background: 'var(--adonis-accent)' }}></div>
          板载外设
        </h1>
      </div>

      <div class="grid grid-cols-1 md:grid-cols-2 gap-6 mb-6">

        {/* 蜂鸣器控制卡片 */}
        <div class="adonis-card p-6">
          <h2 class="text-lg font-semibold adonis-section-title mb-6">
            蜂鸣器控制
          </h2>
          
          <div class="space-y-6">
            {/* 蜂鸣器状态显示 */}
            <div class="flex items-center justify-center">
              <div class={`w-16 h-16 rounded-full flex items-center justify-center`}
                   style={{ background: buzzerState ? 'rgba(255,209,102,0.25)' : 'rgba(255,255,255,0.06)', border: '1px solid var(--adonis-border)' }}>
                <svg class={`w-10 h-10`} style={{ color: buzzerState ? 'var(--adonis-warning)' : 'var(--adonis-text-muted)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M15.536 8.464a5 5 0 010 7.072m2.828-9.9a9 9 0 010 12.728M5.586 15H4a1 1 0 01-1-1v-4a1 1 0 011-1h1.586l4.707-4.707C10.923 3.663 12 4.109 12 5v14c0 .891-1.077 1.337-1.707.707L5.586 15z" />
                </svg>
              </div>
            </div>

            {/* 频率控制 */}
            <div class="space-y-3">
              <div class="flex justify-between items-center">
                <label class="text-sm font-medium adonis-section-title">频率 (Hz)</label>
              </div>
              <div class="flex items-center space-x-3">
                <input
                  type="number"
                  min="20"
                  max="20000"
                  step="1"
                  value={buzzerFrequency}
                  onChange={(e) => {
                    const value = parseInt(e.currentTarget.value);
                    if (value >= 20 && value <= 20000) {
                      handleFrequencyChange(value);
                    }
                  }}
                  disabled={!isConnected.value}
                  class="adonis-input"
                />
                <span class="text-sm" style={{ color: 'var(--adonis-text-muted)' }}>Hz</span>
              </div>
              <input
                type="range"
                min="20"
                max="20000"
                step="100"
                value={buzzerFrequency}
                onChange={(e) => handleFrequencyChange(parseInt(e.currentTarget.value))}
                disabled={!isConnected.value}
                class="w-full slider cursor-pointer disabled:cursor-not-allowed"
                style={{
                  background: `linear-gradient(to right, var(--adonis-accent) 0%, var(--adonis-accent) ${((buzzerFrequency - 20) / (20000 - 20)) * 100}%, #1b2333 ${((buzzerFrequency - 20) / (20000 - 20)) * 100}%, #1b2333 100%)`
                }}
              />
              <div class="flex justify-between text-xs" style={{ color: 'var(--adonis-text-muted)' }}>
                <span>20 Hz</span>
                <span>20K Hz</span>
              </div>
            </div>

            {/* 开关控制 */}
            <div class="flex justify-center">
              <button
                onClick={handleBuzzerToggle}
                disabled={!isConnected.value}
                class={`adonis-btn ${buzzerState ? 'adonis-btn-danger' : 'adonis-btn-success'}`}
              >
                {buzzerState ? '关闭' : '开启'}
              </button>
            </div>
          </div>
        </div>

        {/* 温度传感器卡片 */}
        <div class="adonis-card p-6 flex flex-col">
          <h2 class="text-lg font-semibold adonis-section-title mb-6">
            温度传感器 DS18B20
          </h2>
          
          <div class="flex flex-col items-center justify-center flex-1">
            <div class="text-6xl font-bold mb-2 text-center" style={{ color: 'var(--adonis-danger)' }}>
              {temperature.toFixed(1)}°C
            </div>
            <div class="text-sm text-center" style={{ color: 'var(--adonis-text-muted)' }}>
              <div>精度: ±{Number(accuracy).toFixed(1)}°C</div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

